let sysUserDao = require('../dao/sysUserDao');
let stringUtil = require("../util/stringUtil");
let Token = require('../token');
let cnst = require('../const');
let redisConst = require('../const/redisConst');
let redis=require('../dao/redis');

const { BusiError, SysError } = require('../exception/exception');

class SysUserService {
    constructor() {
    }

    async validSysUser(username, password) {
        let res = await sysUserDao.get(username);
        if (!res){
            console.logw("no this user, username:", username);
            throw new BusiError(500, "no this user, username:" + username);
        }

        console.log("psw=",password)
        password = stringUtil.sha256(password);
        if (res.password === password) {
            let token = JSON.stringify({
                username: username,
                role: res.role,
                timestamp: new Date().getTime()
            });

            let tokenStr = Token.aesEncodeDef(token);

            let cacheKey = redisConst.ADMIN_SYS_TOKEN + ":" + username;
            await redis.set(cacheKey, tokenStr, 7200);

            return tokenStr;
        }

        console.logw("password err:", username, res.role, password);
        throw new BusiError(500, "password err:" + username);
    }

    async validToken (tokenStr) {
        let tokenTmp = Token.aesDecodeDef(tokenStr);
        if (!tokenTmp) return null;

        let token = JSON.parse(tokenTmp);
        if (!token) throw new BusiError(500, "token err:" + tokenStr);

        // todo: 24小时校验
        console.logw("token timestamp:", token.timestamp);

        //
        let cacheKey = redisConst.ADMIN_SYS_TOKEN + ":" + token.username;
        let res = await redis.get(cacheKey);
        if (!res || res !== tokenStr) {
            throw new BusiError(500, "token err[1]:" + tokenStr);
        }

        await redis.set(cacheKey, tokenStr, 7200);
        return token;
    }
}

let sysUserService = new SysUserService();
module.exports = sysUserService;